package com.ycy.leetcode.link;

import org.junit.Test;

import java.util.Arrays;

public class HeBingDemo {

  @Test
  public void test1() {
    //
    int[] arr = new int[]{1, 3, 6, 7, 20, 30};
    int[] brr = new int[]{2, 5, 8, 9};

    int[] newarr = new int[arr.length + brr.length];

    int newarrCur = 0;

    int arrCur = 0;
    int brrCur = 0;

    while (arrCur < arr.length || brrCur < brr.length) {
      if (arrCur >= arr.length || (brrCur < brr.length && arr[arrCur] > brr[brrCur])) {
        newarr[newarrCur++] = brr[brrCur++];
      } else
//        if (brrCur >= brr.length || (arrCur < arr.length && arr[arrCur] <= brr[brrCur]))
      {
        newarr[newarrCur++] = arr[arrCur++];
      }
    }

    System.out.println(Arrays.toString(newarr));

  }

  @Test
  public void test() {
    //链表合并
    Node a = new Node(1);
    Node a1 = new Node(3);
    a.next = a1;
    Node a2 = new Node(10);
    a1.next = a2;

    Node b = new Node(2);
    Node b2 = new Node(100);
    b.next = b2;
//    Node b3 = new Node(5);
//    b2.next = b3;

    Node acurrent = a;
    Node bcurrent = b;

    print(a);

    Node target = null;
    Node targetCur = null;
    while (acurrent != null || bcurrent != null) {
      if ((acurrent == null)) {

        if (targetCur == null) {
          targetCur = bcurrent;
          target = targetCur;
        } else {
          targetCur.next = bcurrent;
          targetCur = targetCur.next;
        }
        bcurrent = bcurrent.next;

      } else if (bcurrent == null) {

        if (targetCur == null) {
          targetCur = acurrent;
          target = targetCur;
        } else {
          targetCur.next = acurrent;
          targetCur = targetCur.next;
        }
        acurrent = acurrent.next;

      } else if (acurrent.val > bcurrent.val) {

        if (targetCur == null) {
          targetCur = bcurrent;
          target = targetCur;
        } else {
          targetCur.next = bcurrent;
          targetCur = targetCur.next;
        }
        bcurrent = bcurrent.next;

      } else {

        if (targetCur == null) {
          targetCur = acurrent;
          target = targetCur;
        } else {
          targetCur.next = acurrent;
          targetCur = targetCur.next;
        }
        acurrent = acurrent.next;

      }

    }

    print(target);

  }


  public void print(Node node) {
    Node cur = node;
    while (cur != null) {
      System.out.print(cur.val + ",");
      cur = cur.next;
    }
    System.out.println();
  }

  class Node {
    int val;
    Node next;

    public Node(int val) {
      this.val = val;
    }
  }

}
